/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.model.Application;
import net.risesoft.risebi.collection.model.Catalog;
import net.risesoft.risebi.collection.model.DbColumn;
import net.risesoft.risebi.collection.model.Notification;
import net.risesoft.risebi.collection.model.NotificationAttachment;
import net.risesoft.risebi.collection.model.NotificationReceiver;
import net.risesoft.risebi.collection.model.ReportWindowPeriod;
import net.risesoft.risebi.collection.model.StatisticalObjectTreeNode;
import net.risesoft.risebi.collection.model.Template;
import net.risesoft.risebi.collection.model.User;
import net.risesoft.risebi.collection.service.ApplicationManager;
import net.risesoft.risebi.collection.service.CatalogManager;
import net.risesoft.risebi.collection.service.DbMetaDataManager;
import net.risesoft.risebi.collection.service.DynaBeanManager;
import net.risesoft.risebi.collection.service.NotificationAttachmentManager;
import net.risesoft.risebi.collection.service.NotificationManager;
import net.risesoft.risebi.collection.service.NotificationReceiverManager;
import net.risesoft.risebi.collection.service.NotificationReplyManager;
import net.risesoft.risebi.collection.service.ServiceManager;
import net.risesoft.risebi.collection.service.StatisticalObjectTreeNodeManager;
import net.risesoft.risebi.collection.service.UserManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

/**
 * NotificationAction
 *
 * @author <a href="mailto: dingzhaojun@risesoft.net">丁兆俊</a>
 * @version $Revision$
 * 
A custom Result type for sending raw data (via an InputStream) directly to the HttpServletResponse. Very useful for allowing users to download content.
    * contentType - the stream mime-type as sent to the web browser (default = text/plain).
    * contentLength - the stream length in bytes (the browser displays a progress bar).
    * contentDisposition - the content disposition header value for specifing the file name (default = inline, values are typically attachment;filename="document.pdf".
    * inputName - the name of the InputStream property from the chained action (default = inputStream).
    * bufferSize - the size of the buffer to copy from input to output (default = 1024).
    * allowCaching if set to 'false' it will set the headers 'Pragma' and 'Cache-Control' to 'no-cahce', and prevent client from caching the content. (default = true)
    * contentCharSet if set to a string, ';charset=value' will be added to the content-type header, where value is the string set. If set to an expression, the result of evaluating the expression will be used. If not set, then no charset will be set on the header

These parameters can also be set by exposing a similarly named getter method on your Action. For example, you can provide getContentType() to override that parameter for the current action.
Examples

<result name="success" type="stream">
  <param name="contentType">image/jpeg</param>
  <param name="inputName">imageStream</param>
  <param name="contentDisposition">attachment;filename="document.pdf"</param>
  <param name="bufferSize">1024</param>
</result>
 * 
 */

public class BaseNotificationAction extends BaseAction{
	private static final long serialVersionUID = -5348665261143362121L;
	private static Log log = LogFactory.getLog(BaseNotificationAction.class);
	
	private ServiceManager serviceManager;
	private ApplicationManager applicationManager;
	private CatalogManager catalogManager;
	private DynaBeanManager dynaBeanManager;
	private NotificationManager notificationManager;
	private NotificationAttachmentManager notificationAttachmentManager;
	private NotificationReceiverManager notificationReceiverManager;
	private NotificationReplyManager notificationReplyManager;
	private StatisticalObjectTreeNodeManager statisticalObjectTreeNodeManager;
	private DbMetaDataManager dbMetaDataManager;
	private UserManager userManager;

	private HashMap<String,Object> dynaBean;
	private Notification notification;
	private NotificationReceiver notificationReceiver;

	private String crud;
	private String currentUserGuid;
	private String applicationGuid;
	private String startDate;
	private String endDate;
	private String classify;
	private String filter;
	private Boolean addAllReceivers;

	//以下三个字段用于文件上载
	private File attachment;
	private String attachmentFileName;
	private String attachmentContentType;
	
	//以下七个字段用于文件下载
	private InputStream fileStream;
	private String contentType;
	private String contentDisposition;
	private String contentCharSet;
	private int bufferSize = 4096;
	private int contentLength;
	private boolean allowCaching = false;	

	@SuppressWarnings("unchecked")
	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		try{
			if("jsonList".equalsIgnoreCase(this.whichJson)){
				if(this.notification==null){
					this.notification = new Notification();
				}
				
				String filter = "";
				Date d = notification.getStartTime();
				if(d==null){
					if(this.startDate!=null){
						filter = "n.startTime between '" + this.startDate + "' and '" + this.endDate + "'"; 
					}
				}else{
					Calendar calendar = new GregorianCalendar();
					calendar.setTime(d);
					int year = calendar.get(Calendar.YEAR);
					int month = calendar.get(Calendar.MONTH) + 1;
					int day = calendar.get(Calendar.DAY_OF_MONTH);
					
					filter = "year(n.startTime)=" + year + " and month(n.startTime)=" + month + " and day(n.startTime)=" + day;
					notification.setStartTime(null);
				}
				
				User user = this.getSessionUser();
				Map mapNotifications = notificationManager.getPagedByNotification(user, notification, "n", filter, this.start, this.limit);
				List<Notification> list = (List<Notification>)mapNotifications.get("list");
				
				List newList = new ArrayList();
				for(Notification n : list){
					Map m = new HashMap();					
					m.put("guid", n.getGuid());
					m.put("title", n.getTitle());
					m.put("type", n.getType());					
					m.put("classify", n.getClassify());
					if(n.getStartTime()==null){
						m.put("startTime", "");
					}else{
						m.put("startTime", DateFormatUtils.format(n.getStartTime(),"yyyy-MM-dd"));
					}
					m.put("endTime", n.getEndTime());
					m.put("content", n.getContent());
					
					if(n.getWriter_GUID()==null){
						m.put("writer_GUID", "");
						m.put("writerName", "");
					}else{
						m.put("writer_GUID", n.getWriter_GUID());
						User writerUser = (User)userManager.getObject(User.class, n.getWriter_GUID());
						if(writerUser!=null){
							m.put("writerName", writerUser.getRealName());
						}else{
							m.put("writerName", "");
						}
					}					
					
					int attachments = notificationAttachmentManager.getCount("select count(*) from NotificationAttachment t where t.notification.guid='" + n.getGuid() + "'");
					m.put("attachments", attachments);
					
					int readedReceivers = notificationReceiverManager.getCount("select count(*) from NotificationReceiver t where t.notification.guid='" + n.getGuid() + "' and t.readStatus=true");
					int unreadReceivers = notificationReceiverManager.getCount("select count(*) from NotificationReceiver t where t.notification.guid='" + n.getGuid() + "' and t.readStatus=false");
					m.put("readStatus", "已读" + readedReceivers + ",未读" + unreadReceivers);
					newList.add(m);
				}
				
				//mapNotifications.put("count", count);
				mapNotifications.put("list", newList);
				this.json = JSONUtil.getJsonString(null,null,mapNotifications);
			}else if("jsonAttachments".equalsIgnoreCase(this.whichJson)){
				List<NotificationAttachment> list = notificationAttachmentManager.find("from NotificationAttachment t where t.notification.guid='" + notification.getGuid() + "' order by tabIndex asc");
				List newList = new ArrayList();
				for(NotificationAttachment na : list){
					Map m = new HashMap();	
					m.put("guid", na.getGuid());
					m.put("href", this.getContextPath() + "/client/NotificationAction/download.action?node=" + na.getGuid());
					//m.put("href", "/${ctx}/client/NotificationAction/download.action?node=" + na.getGuid());
					m.put("name", na.getName());
					m.put("extension", na.getExtension());
					m.put("size", na.getSize());
					m.put("tabIndex", na.getTabIndex());
					newList.add(m);
				}
				this.json = JSONUtil.getJsonString(null,null,newList);
			}else if("jsonAttachments2".equalsIgnoreCase(this.whichJson)){
				List newList = new ArrayList();
				notification = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
				if(notification!=null && notification.getContentFileFileName()!=null){
					Map m = new HashMap();	
					m.put("name", notification.getContentFileFileName());
					m.put("size", notification.getFileSize());
					newList.add(m);
				}
				this.json = JSONUtil.getJsonString(null,null,newList);
			}else if("jsonReceivers".equalsIgnoreCase(this.whichJson)){
				if(this.addAllReceivers!=null && this.addAllReceivers==true){
					try{
						notificationReceiverManager.execute("delete NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "'");
						
						Notification note = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
						if(note==null){
							notificationManager.saveObject(notification);
						}
						
						List<Catalog> soList = catalogManager.getCatalogWithSoByService(this.getDefaultService().getGuid());
						for(Catalog so : soList){
							String tableName = so.getTableName().trim().toLowerCase();
							List<HashMap<String,Object>> list = dynaBeanManager.getObjects(tableName);
							for(HashMap<String,Object> map : list){
								NotificationReceiver r = new NotificationReceiver();
								r.setGuid(new GUID().toString(32));

								String soInstanceGuid = map.get("item_guid").toString();
								String soInstanceName = map.get("item_name").toString();
								r.setNotification(notification);
								r.setSoGuid(this.node);
								r.setSoInstanceGuid(soInstanceGuid);
								r.setSoInstanceName(soInstanceName);
								r.setDeleted(false);
								r.setReadStatus(false);
								r.setReplied(false);
								notificationReceiverManager.saveObject(r);
							}
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				}
				
				if(this.notificationReceiver==null){
					this.notificationReceiver = new NotificationReceiver();
				}
				Map mapReceivers = notificationReceiverManager.getPagedReceivers(notificationReceiver, "t", "t.notification.guid='" + notification.getGuid() + "' and t.deleted=false", this.start, this.limit);
				List<NotificationReceiver> list = (List<NotificationReceiver>)mapReceivers.get("list");
				List newList = new ArrayList();
				for(NotificationReceiver r : list){
					Map m = new HashMap();
					m.put("guid", r.getGuid());
					m.put("soGuid", r.getSoGuid());
					m.put("soInstanceGuid", r.getSoInstanceGuid());
					m.put("soInstanceName", r.getSoInstanceName());					
					m.put("readStatus", r.getReadStatus());
					m.put("replied", r.getReplied());
					m.put("deleted", r.getDeleted());
					
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					if(r.getReadTime()==null){
						m.put("readTime", "未读");
					}else{
						m.put("readTime", sdf.format(r.getReadTime()));
					}
					
					newList.add(m);
				}		
				mapReceivers.put("list", newList);
				this.json = JSONUtil.getJsonString(null,null,mapReceivers);
			}else if("jsonSoByApp".equalsIgnoreCase(this.whichJson)){
				List<Catalog> lst = catalogManager.getCatalogWithSoByApp(this.applicationGuid,false);
				List newList = new ArrayList();
				for(Catalog t : lst){
					Map map = new HashMap();
					map.put("guid", t.getGuid());
					map.put("name", t.getName());
					newList.add(map);
				}
				this.json = JSONUtil.getJsonString(null,null,newList);

				return AJAX;
			}else if("jsonGroupbyFieldsBySo".equalsIgnoreCase(this.whichJson)){
				List<StatisticalObjectTreeNode> list = statisticalObjectTreeNodeManager.getAllBySoGuid(this.node);
				List newList = new ArrayList();
				for(StatisticalObjectTreeNode n : list){
					Map map = new HashMap();
					
					String fieldName = n.getSelfColumnName().trim().toLowerCase();
					String fieldCaption = "";
					Catalog so = n.getCatalog();
					List<DbColumn> lst1 = dbMetaDataManager.listAllColumns(so.getTableName());
					for(DbColumn f : lst1){
						if(f.getColumn_name().equalsIgnoreCase(fieldName)){
							fieldCaption = f.getComment().trim();
							break;
						}
					}
					
					String parentFieldName = n.getParentColumnName().trim().toLowerCase();
					String parentTableName = n.getParentStatisticalObjectTreeNode().getCatalog().getTableName().trim().toLowerCase();		
					
					map.put("checked", false);
					map.put("fieldName", fieldName);
					map.put("fieldCaption", fieldCaption);
					map.put("parentTableName", parentTableName);
					map.put("parentFieldName", parentFieldName);
					newList.add(map);
				}
				this.json = JSONUtil.getJsonString(null,null,newList);

				return AJAX;
			}else if("jsonSoItems".equalsIgnoreCase(this.whichJson)){
				Catalog catalog = (Catalog)catalogManager.getObject(Catalog.class, this.node);
				String tableName = catalog.getTableName().trim().toLowerCase();
				String filters = "";
				if(this.filter!=null){
					filters = this.filter.trim();
				}
				if(dynaBean!=null){
					Object item_name = dynaBean.get("item_name");
					Object item_code = dynaBean.get("item_code");
					if(item_name!=null && item_name.toString().trim().length()>0){
						if(filters.length()==0){
							filters = "t.item_name like '%" + item_name.toString().trim() + "%'";
						}else{
							filters += " and t.item_name like '%" + item_name.toString().trim() + "%'";
						}
					}
					if(item_code!=null && item_code.toString().trim().length()>0){							
						if(filters.length()==0){
							filters = "t.item_code like '%" + item_code.toString().trim() + "%'";
						}else{
							filters += " and t.item_code like '%" + item_code.toString().trim() + "%'";
						}
					}						
				}
				
				if(filters.length()==0){
					filters = "t.item_guid not in (select r.soInstanceGuid from NotificationReceiver r where r.notification.guid='" + notification.getGuid() + "')";
				}else{
					filters += " and t.item_guid not in (select r.soInstanceGuid from NotificationReceiver r where r.notification.guid='" + notification.getGuid() + "')";
				}
				
				Map map = dynaBeanManager.getPagedSoItems(tableName, "t", filters, this.start, this.limit);
				this.json = JSONUtil.getJsonString(null, null, map);
			}else if("jsonGroupbyTreeGrid".equalsIgnoreCase(this.whichJson)){
				String[] str = this.source.split(";");
				if(this.active_node_id==null || this.active_node_id.trim().length()==0){					
					boolean isLeaf = true;
					if(str.length > 1){
						isLeaf = false;
					}
					
					String[] array =  str[0].split(",");
					String parentTableName = array[0];
					String parentFieldName = array[1];
					String fieldName = array[2];
					
					Map map = dynaBeanManager.getPagedSoItems(parentTableName, "t", "", this.start, this.limit);
					List list = (List)map.get("list");
					List newlist = new ArrayList();
					for(Object row : list){
						Map rs = (Map)row;
						HashMap hm = new HashMap(); 
						hm.put("parentId", null);
						hm.put("id", rs.get("item_guid"));
						hm.put("item_name", rs.get("item_name"));
						hm.put("_node_type", parentTableName);
						hm.put("fieldName", fieldName);
						hm.put("fieldValue", rs.get(parentFieldName));
						hm.put("_is_leaf", isLeaf);	
						newlist.add(hm);
					}
					map.put("list", newlist);
					this.json = JSONUtil.getJsonString(null, null, map);
				}else{
					int index = 0;
					for(int i=0; i<str.length; i++){
						if(str[i].contains(this.active_node_type)){
							index = i+1;
							break;
						}
					}

					boolean isLeaf = true;
					if(str.length-1 > index){
						isLeaf = false;
					}
					
					String[] array =  str[index].split(",");
					String parentTableName = array[0];
					String parentFieldName = array[1];
					String fieldName = array[2];					
					
					Map map = dynaBeanManager.getPagedSoItems(parentTableName, "t", "", this.start, this.limit);
					List list = (List)map.get("list");
					List newlist = new ArrayList();
					for(Object row : list){
						Map rs = (Map)row;
						HashMap hm = new HashMap(); 
						hm.put("parentId", this.active_node_id);
						hm.put("id", this.active_node_id + rs.get("item_guid"));
						hm.put("item_name", rs.get("item_name"));
						hm.put("_node_type", parentTableName);
						hm.put("fieldName", fieldName);
						hm.put("fieldValue", rs.get(parentFieldName));
						hm.put("_is_leaf", isLeaf);	
						newlist.add(hm);						
					}
					map.put("list", newlist);
					this.json = JSONUtil.getJsonString(null, null, map);
				}								
			}
		}catch(Exception e){
			this.json = "[]";
			e.printStackTrace();
		} 

		return AJAX;
	}
	
	@Action(value="list",
			results={@Result(name="success", location="/client/notification/notificationList.jsp")}
	)
	public String list() throws Exception {
		this.currentUserGuid = this.getSessionUser().getGuid();
		
		return SUCCESS;
	}	

	@Action(value="list2",
			results={@Result(name="success", location="/client/notification2/notificationList.jsp")}
	)
	public String list2() throws Exception {
		this.currentUserGuid = this.getSessionUser().getGuid();
		
		return SUCCESS;
	}
	
	@Action(value="prepareEdit",
			results={@Result(name="success", location="/client/notification/notificationEdit.jsp")}
	)
	public String prepareEdit() throws Exception {
		this.currentUserGuid = this.getSessionUser().getGuid();
		String guid = notification.getGuid();
		if(guid==null || guid.trim().length()==0){
			notification = new Notification();
			notification.setGuid(new GUID().toString(32));
		}else{
			notification = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
			
			String content = notification.getContent();
			content = content.replace("${ctx}/client/NotificationAction/download.action", this.getContextPath() + "/client/NotificationAction/download.action");
			notification.setContent(content);
		}
		
		return SUCCESS;
	}

	@Action(value="prepareEdit2",
			results={@Result(name="success", location="/client/notification2/notificationEdit.jsp")}
	)
	public String prepareEdit2() throws Exception {
		this.currentUserGuid = this.getSessionUser().getGuid();
		String guid = notification.getGuid();
		if(guid==null || guid.trim().length()==0){
			notification = new Notification();
			notification.setGuid(new GUID().toString(32));
		}else{
			notification = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
		}
		
		return SUCCESS;
	}
	
	@Action(value="prepareView",
			results={@Result(name="success", location="/client/notification/notificationView.jsp")}
	)
	public String prepareView() throws Exception {
		notification = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
		source = notification.getContent();
		source = source.replace("${ctx}", this.getContextPath());
		
		User user = this.getSessionUser();
		if(user.getUserType()==User.USERTYPE_ENTERPRISEUSER){
			List<NotificationReceiver> listReceivers = notificationReceiverManager.find("from NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "' and t.soInstanceGuid in (select s.soInstanceGuid from UserSO s where s.user.guid='" + user.getGuid() + "')");
			if(listReceivers.size()>0){						
				for(NotificationReceiver r : listReceivers){
					r.setReadStatus(true);
					r.setReadTime(new Date());
					notificationReceiverManager.saveObject(r);
				}
			}
		}		
		
		return SUCCESS;
	}	
	
	@Action(value="prepareSearch",
			results={@Result(name="success", location="/client/notification/notificationSearch.jsp")}
	)
	public String prepareSearch() throws Exception {		
		return SUCCESS;
	}

	@Action(value="prepareSearch2",
			results={@Result(name="success", location="/client/notification2/notificationSearch.jsp")}
	)
	public String prepareSearch2() throws Exception {		
		return SUCCESS;
	}
	
	@Action(value="prepareSelectSoItemsFromApp",
			results={@Result(name="success", location="/client/notification/selectSoItemsFromApp.jsp")}
	)
	public String prepareSelectSoItemsFromApp() throws Exception {
		ArrayList newList = new ArrayList();
		List<Application> list = applicationManager.getAppsByServiceWithPermission(this.getDefaultService().getGuid(), this.getSessionUser());
		for(Application a : list){
			Map map = new  HashMap();	
			map.put("guid", a.getGuid());
			map.put("name", a.getChineseName());
			newList.add(map);
		}		
		this.json = JSONUtil.getJsonString(null, null, newList);	
		
		return SUCCESS;
	}

	@Action(value="prepareSelectSoItemsFromApp2",
			results={@Result(name="success", location="/client/notification2/selectSoItemsFromApp.jsp")}
	)
	public String prepareSelectSoItemsFromApp2() throws Exception {
		ArrayList newList = new ArrayList();
		List<Application> list = applicationManager.getAppsByServiceWithPermission(this.getDefaultService().getGuid(), this.getSessionUser());
		for(Application a : list){
			Map map = new  HashMap();	
			map.put("guid", a.getGuid());
			map.put("name", a.getChineseName());
			newList.add(map);
		}		
		this.json = JSONUtil.getJsonString(null, null, newList);	
		
		return SUCCESS;
	}
	
	@Action(value="prepareAddAttachments",
			results={@Result(name="success", location="/client/notification/addAttachments.jsp")}
	)
	public String prepareAddAttachments() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareAddAttachments2",
			results={@Result(name="success", location="/client/notification2/addAttachments.jsp")}
	)
	public String prepareAddAttachments2() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareReadStatus",
			results={@Result(name="success", location="/client/notification/readStatus.jsp")}
	)
	public String prepareReadStatus() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="prepareReadStatus2",
			results={@Result(name="success", location="/client/notification2/readStatus.jsp")}
	)
	public String prepareReadStatus2() throws Exception {
		return SUCCESS;
	}
	
	@Action(value="edit")
	public String edit() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			String content = notification.getContent();
			content = content.replace(this.getContextPath() + "/client/NotificationAction/download.action", "${ctx}/client/NotificationAction/download.action");
			notification.setContent(content);
			
			Notification note = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
			notification.setWriter_GUID(this.getSessionUser().getGuid());
			if(note==null){
				notificationManager.saveObject(notification);
			}else{
				note.setContent(notification.getContent());
				note.setEndTime(notification.getEndTime());
				note.setStartTime(notification.getStartTime());
				note.setTitle(notification.getTitle());
				note.setType(notification.getType());
				note.setWriter_GUID(notification.getWriter_GUID());
				note.setClassify(notification.getClassify());
				notificationManager.saveObject(note);				
			}						

			ldb.set("success", true);
			ldb.set("reason", "保存成功！");
			
			ldb.set("guid", notification.getGuid());
			ldb.set("title", notification.getTitle());
			ldb.set("type", notification.getType());
			
			Date d = notification.getStartTime();
			if(d!=null){
				ldb.set("startTime", DateFormatUtils.format(d,"yyyy-MM-dd HH:mm:ss"));
			}else{
				ldb.set("startTime", DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
			}
			
			d = notification.getEndTime();
			if(d!=null){
				ldb.set("endTime", DateFormatUtils.format(d,"yyyy-MM-dd HH:mm:ss"));
			}else{
				ldb.set("endTime", "");
			}			
			
			User user = (User)userManager.getObject(User.class, notification.getWriter_GUID());
			ldb.set("writerName", user.getRealName());
			ldb.set("writer_GUID", notification.getWriter_GUID());
			ldb.set("content", notification.getContent());

			int attachments = notificationAttachmentManager.getCount("select count(*) from NotificationAttachment t where t.notification.guid='" + notification.getGuid() + "'");
			ldb.set("attachments", attachments);
			
			int readedReceivers = notificationReceiverManager.getCount("select count(*) from NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "' and t.readStatus=true");
			int unreadReceivers = notificationReceiverManager.getCount("select count(*) from NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "' and t.readStatus=false");
			ldb.set("readStatus", "已读" + readedReceivers + ",未读" + unreadReceivers);
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}

	@Action(value="edit2",
			results={@Result(name="ajax", type="ajax",params={"contentType","text/html"})}
	)
	public String edit2() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Notification note = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
			notification.setWriter_GUID(this.getSessionUser().getGuid());
			if(note==null){
				notificationManager.saveObject(notification);
			}else{
				note.setEndTime(notification.getEndTime());
				note.setStartTime(notification.getStartTime());
				note.setTitle(notification.getTitle());
				note.setType(notification.getType());
				note.setWriter_GUID(notification.getWriter_GUID());
				note.setClassify(notification.getClassify());
				notificationManager.saveObject(note);				
			}						

			ldb.set("success", true);
			ldb.set("reason", "保存成功！");
			
			ldb.set("guid", notification.getGuid());
			ldb.set("title", notification.getTitle());
			ldb.set("type", notification.getType());
			
			Date d = notification.getStartTime();
			if(d!=null){
				ldb.set("startTime", DateFormatUtils.format(d,"yyyy-MM-dd HH:mm:ss"));
			}else{
				ldb.set("startTime", DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
			}
			
			d = notification.getEndTime();
			if(d!=null){
				ldb.set("endTime", DateFormatUtils.format(d,"yyyy-MM-dd HH:mm:ss"));
			}else{
				ldb.set("endTime", "");
			}			
			
			User user = (User)userManager.getObject(User.class, notification.getWriter_GUID());
			ldb.set("writerName", user.getRealName());
			ldb.set("writer_GUID", notification.getWriter_GUID());
			ldb.set("content", notification.getContent());

			int attachments = notificationAttachmentManager.getCount("select count(*) from NotificationAttachment t where t.notification.guid='" + notification.getGuid() + "'");
			ldb.set("attachments", attachments);
			
			int readedReceivers = notificationReceiverManager.getCount("select count(*) from NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "' and t.readStatus=true");
			int unreadReceivers = notificationReceiverManager.getCount("select count(*) from NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "' and t.readStatus=false");
			ldb.set("readStatus", "已读" + readedReceivers + ",未读" + unreadReceivers);
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}
	
	@Action(value="upload",
			results={@Result(name="ajax", type="ajax",params={"contentType","text/html"})}
	)
	public String upload() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Notification note = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
			if(note==null){
				notificationManager.saveObject(notification);
			}

			NotificationAttachment na = new NotificationAttachment();
			na.setGuid(new GUID().toString(32));
			na.setExtension(FilenameUtils.getExtension(this.attachmentFileName));
			na.setName(this.attachmentFileName);
			na.setNotification(notification);
			na.setSize(String.valueOf(this.attachment.length()));
			na.setTabIndex(1d);
			na.setContent(FileUtils.readFileToByteArray(this.attachment));
			notificationAttachmentManager.saveObject(na);
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}
		
		return AJAX;
	}
	
	@Action(value="upload2",
			results={@Result(name="ajax", type="ajax",params={"contentType","text/html"})}
	)
	public String upload2() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			String guid = notification.getGuid();
			notification = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
			if(notification==null){				
				notification = new Notification();
				notification.setGuid(guid);
			}
			
			notification.setContentFileFileName(this.attachmentFileName);
			notification.setFileSize(String.valueOf(this.attachment.length()));
			notification.setContentFileContentType(this.attachmentContentType);
			notification.setContentFile(FileUtils.readFileToByteArray(this.attachment));
			notificationManager.saveObject(notification);
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}
		
		return AJAX;
	}
	
	@Action(value="download",
			results={@Result(name="success", type="stream",params={"inputName","fileStream"})}
	)
	public String download() throws Exception {
		ByteArrayInputStream bais = null;
		
		try{
			NotificationAttachment na = (NotificationAttachment)notificationAttachmentManager.getObject(NotificationAttachment.class, node);
			
			byte[] b = na.getContent();
			
			bais = new ByteArrayInputStream(b);
			this.fileStream = bais;
			this.contentLength = b.length;
			this.contentType = "application/octet-stream";
			//this.contentType = "application/force-download";
			this.contentDisposition = "attachment; filename=" + na.getName();
			
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
		}
				
		return SUCCESS;
	}
	
	@Action(value="download2",
			results={@Result(name="success", type="stream",params={"inputName","fileStream"})}
	)
	public String download2() throws Exception {
		ByteArrayInputStream bais = null;
		
		try{
			notification = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
			User user = this.getSessionUser();
			if(user.getUserType()==User.USERTYPE_ENTERPRISEUSER){
				List<NotificationReceiver> listReceivers = notificationReceiverManager.find("from NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "' and t.soInstanceGuid in (select s.soInstanceGuid from UserSO s where s.user.guid='" + user.getGuid() + "')");
				if(listReceivers.size()>0){						
					for(NotificationReceiver r : listReceivers){
						r.setReadStatus(true);
						r.setReadTime(new Date());
						notificationReceiverManager.saveObject(r);
					}
				}
			}
			
			byte[] b = notification.getContentFile();
			
			bais = new ByteArrayInputStream(b);
			this.fileStream = bais;
			this.contentLength = b.length;
			this.contentType = notification.getContentFileContentType();
			//this.contentType = "application/force-download";
			this.contentDisposition = "inline; filename=" + notification.getContentFileFileName();
			
			return SUCCESS;
		}catch(Exception e){
			e.printStackTrace();
		}
				
		return SUCCESS;
	}
	
	@Action(value="addReceivers")
	public String addReceivers() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			Notification note = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
			if(note==null){
				notificationManager.saveObject(notification);
			}
			
			Catalog catalog = (Catalog)catalogManager.getObject(Catalog.class, this.node);
			String tableName = catalog.getTableName().trim().toLowerCase();
			if("all".equals(this.source)){
				if(this.filter==null){
					this.filter = "";
					
				}
				//List<HashMap<String,Object>> list = dynaBeanManager.getAllDataWithFilter(tableName, "t", "t.item_guid, t.item_name", filter);
				List<HashMap<String,Object>> list = dynaBeanManager.getAllDataWithFilter(tableName, "t", "", filter);
				
				for(HashMap<String,Object> map : list){
					NotificationReceiver r = new NotificationReceiver();
					r.setGuid(new GUID().toString(32));

					String soInstanceGuid = map.get("item_guid").toString();
					String soInstanceName = map.get("item_name").toString();
					List<NotificationReceiver> listReceivers = notificationReceiverManager.find("from NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "' and t.soGuid='" + this.node + "' and t.soInstanceGuid='" + soInstanceGuid + "'");
					if(listReceivers.size()>0){						
						r = listReceivers.get(0);
					}
					r.setNotification(notification);
					r.setSoGuid(this.node);
					r.setSoInstanceGuid(soInstanceGuid);
					r.setSoInstanceName(soInstanceName);
					r.setDeleted(false);
					r.setReadStatus(false);
					r.setReplied(false);
					notificationReceiverManager.saveObject(r);
				}
			}else{
				String[] soInstanceGuids = this.source.split(",");
				for(String soInstanceGuid : soInstanceGuids){
					dynaBean = (HashMap<String,Object>)dynaBeanManager.getObject(tableName, soInstanceGuid);
					String soInstanceName = dynaBean.get("item_name").toString();
					NotificationReceiver r = new NotificationReceiver();
					r.setNotification(notification);
					r.setSoGuid(this.node);
					r.setSoInstanceGuid(soInstanceGuid);
					r.setSoInstanceName(soInstanceName);
					r.setDeleted(false);
					r.setReadStatus(false);
					r.setReplied(false);
					r.setGuid(new GUID().toString(32));
					notificationReceiverManager.saveObject(r);
				}
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功！");
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}
	
	@Action(value="addAllReceivers")
	public String addAllReceivers() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			notificationReceiverManager.execute("delete NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "'");
			
			Notification note = (Notification)notificationManager.getObject(Notification.class, notification.getGuid());
			if(note==null){
				notificationManager.saveObject(notification);
			}
			
			List<Catalog> soList = catalogManager.getCatalogWithSoByService(this.getDefaultService().getGuid());
			for(Catalog so : soList){
				String tableName = so.getTableName().trim().toLowerCase();
				List<HashMap<String,Object>> list = dynaBeanManager.getObjects(tableName);
				for(HashMap<String,Object> map : list){
					NotificationReceiver r = new NotificationReceiver();
					r.setGuid(new GUID().toString(32));

					String soInstanceGuid = map.get("item_guid").toString();
					String soInstanceName = map.get("item_name").toString();
					//List<NotificationReceiver> listReceivers = notificationReceiverManager.find("from NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "' and t.soGuid='" + so.getGuid() + "' and t.soInstanceGuid='" + soInstanceGuid + "'");
					//if(listReceivers.size()>0){						
					//	r = listReceivers.get(0);
					//}
					r.setNotification(notification);
					r.setSoGuid(this.node);
					r.setSoInstanceGuid(soInstanceGuid);
					r.setSoInstanceName(soInstanceName);
					r.setDeleted(false);
					r.setReadStatus(false);
					r.setReplied(false);
					notificationReceiverManager.saveObject(r);
				}
			}

			ldb.set("success", true);
			ldb.set("reason", "保存成功！");
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}
		
		return AJAX;
	}
	
	@Action(value="removeReceivers")
	public String removeReceivers() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if("all".equals(this.source)){
				notificationReceiverManager.execute("delete from NotificationReceiver t where t.notification.guid='" + notification.getGuid() + "'");
			}else{
				String[] ss = this.source.split(",");
				for(String s : ss){
					notificationReceiverManager.execute("delete from NotificationReceiver t where t.guid='" + s + "'");
				}
			}
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}
	
	@Action(value="removeAttachments")
	public String removeAttachments() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if("all".equals(this.source)){
				notificationAttachmentManager.execute("delete from NotificationAttachment t where t.notification.guid='" + notification.getGuid() + "'");
			}else{
				String[] ss = this.source.split(",");
				for(String s : ss){
					notificationAttachmentManager.execute("delete from NotificationAttachment t where t.guid='" + s + "'");
				}
			}
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}
	
	@Action(value="remove")
	public String remove() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			notificationReplyManager.execute("delete from NotificationReply t where t.notification.guid='" + node + "'");
			notificationReceiverManager.execute("delete from NotificationReceiver t where t.notification.guid='" + node + "'");
			notificationAttachmentManager.execute("delete from NotificationAttachment t where t.notification.guid='" + node + "'");
			notificationManager.execute("delete from Notification t where t.guid='" + node + "'");			
			//notificationManager.removeObject(Notification.class, node); 		
			
			ldb.set("success", true);
			ldb.set("reason", "删除成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}

	public NotificationManager getNotificationManager() {
		return notificationManager;
	}

	public void setNotificationManager(NotificationManager notificationManager) {
		this.notificationManager = notificationManager;
	}

	public Notification getNotification() {
		return notification;
	}

	public void setNotification(Notification notification) {
		this.notification = notification;
	}

	public String getCrud() {
		return crud;
	}

	public void setCrud(String crud) {
		this.crud = crud;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}

	public String getCurrentUserGuid() {
		return currentUserGuid;
	}

	public void setCurrentUserGuid(String currentUserGuid) {
		this.currentUserGuid = currentUserGuid;
	}

	public NotificationAttachmentManager getNotificationAttachmentManager() {
		return notificationAttachmentManager;
	}

	public void setNotificationAttachmentManager(
			NotificationAttachmentManager notificationAttachmentManager) {
		this.notificationAttachmentManager = notificationAttachmentManager;
	}

	public NotificationReceiverManager getNotificationReceiverManager() {
		return notificationReceiverManager;
	}

	public void setNotificationReceiverManager(
			NotificationReceiverManager notificationReceiverManager) {
		this.notificationReceiverManager = notificationReceiverManager;
	}

	public NotificationReplyManager getNotificationReplyManager() {
		return notificationReplyManager;
	}

	public void setNotificationReplyManager(
			NotificationReplyManager notificationReplyManager) {
		this.notificationReplyManager = notificationReplyManager;
	}

	public String getApplicationGuid() {
		return applicationGuid;
	}

	public void setApplicationGuid(String applicationGuid) {
		this.applicationGuid = applicationGuid;
	}

	public ServiceManager getServiceManager() {
		return serviceManager;
	}

	public void setServiceManager(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}

	public ApplicationManager getApplicationManager() {
		return applicationManager;
	}

	public void setApplicationManager(ApplicationManager applicationManager) {
		this.applicationManager = applicationManager;
	}

	public CatalogManager getCatalogManager() {
		return catalogManager;
	}

	public void setCatalogManager(CatalogManager catalogManager) {
		this.catalogManager = catalogManager;
	}

	public DynaBeanManager getDynaBeanManager() {
		return dynaBeanManager;
	}

	public void setDynaBeanManager(DynaBeanManager dynaBeanManager) {
		this.dynaBeanManager = dynaBeanManager;
	}

	public HashMap<String, Object> getDynaBean() {
		return dynaBean;
	}

	public void setDynaBean(HashMap<String, Object> dynaBean) {
		this.dynaBean = dynaBean;
	}

	public File getAttachment() {
		return attachment;
	}

	public void setAttachment(File attachment) {
		this.attachment = attachment;
	}

	public String getAttachmentFileName() {
		return attachmentFileName;
	}

	public void setAttachmentFileName(String attachmentFileName) {
		this.attachmentFileName = attachmentFileName;
	}

	public String getAttachmentContentType() {
		return attachmentContentType;
	}

	public void setAttachmentContentType(String attachmentContentType) {
		this.attachmentContentType = attachmentContentType;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getContentDisposition() {
		return contentDisposition;
	}

	public void setContentDisposition(String contentDisposition) {
		this.contentDisposition = contentDisposition;
	}

	public String getContentCharSet() {
		return contentCharSet;
	}

	public void setContentCharSet(String contentCharSet) {
		this.contentCharSet = contentCharSet;
	}

	public int getBufferSize() {
		return bufferSize;
	}

	public void setBufferSize(int bufferSize) {
		this.bufferSize = bufferSize;
	}

	public int getContentLength() {
		return contentLength;
	}

	public void setContentLength(int contentLength) {
		this.contentLength = contentLength;
	}

	public boolean isAllowCaching() {
		return allowCaching;
	}

	public void setAllowCaching(boolean allowCaching) {
		this.allowCaching = allowCaching;
	}

	public InputStream getFileStream() {
		return fileStream;
	}

	public void setFileStream(InputStream fileStream) {
		this.fileStream = fileStream;
	}

	public NotificationReceiver getNotificationReceiver() {
		return notificationReceiver;
	}

	public void setNotificationReceiver(NotificationReceiver notificationReceiver) {
		this.notificationReceiver = notificationReceiver;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public String getClassify() {
		return classify;
	}

	public void setClassify(String classify) {
		this.classify = classify;
	}

	public StatisticalObjectTreeNodeManager getStatisticalObjectTreeNodeManager() {
		return statisticalObjectTreeNodeManager;
	}

	public void setStatisticalObjectTreeNodeManager(
			StatisticalObjectTreeNodeManager statisticalObjectTreeNodeManager) {
		this.statisticalObjectTreeNodeManager = statisticalObjectTreeNodeManager;
	}

	public DbMetaDataManager getDbMetaDataManager() {
		return dbMetaDataManager;
	}

	public void setDbMetaDataManager(DbMetaDataManager dbMetaDataManager) {
		this.dbMetaDataManager = dbMetaDataManager;
	}

	public String getFilter() {
		return filter;
	}

	public void setFilter(String filter) {
		this.filter = filter;
	}

	public Boolean getAddAllReceivers() {
		return addAllReceivers;
	}

	public void setAddAllReceivers(Boolean addAllReceivers) {
		this.addAllReceivers = addAllReceivers;
	}

}
